﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using Game.Command.Internal;
using Game.Map;
using Game.Map.Extensions;
using Game.Map.Internal;
using Game.Objects;
using Game.Level;
using Game.Command;

namespace Game.Serializer
{
    public static class GameMapSerializer
    {
        public static void Save(GameLevels levels, Stream stream)
        {
            var knownTypes = KnownTypes();

            var serializer =
                new DataContractSerializer(
                    typeof(GameLevels), knownTypes);

            serializer.WriteObject(stream, levels);
        }

        public static void Save(IGameMap gameMap, Stream stream)
        {
            var knownTypes = KnownTypes();

            var serializer =
                new DataContractSerializer(
                    typeof(GameMap), knownTypes);

            serializer.WriteObject(stream, gameMap);
        }

        private static IEnumerable<Type> KnownTypes()
        {
            var knownTypes = new List<Type>
                                 {
                                     typeof (MapField),
                                     typeof (Vehicle),
                                     typeof (GameMap),
                                     typeof (GameBuilding),
                                     typeof (GameObject),
                                     typeof (GameLevel),
                                     typeof (GameMilestone),
                                     typeof (BuildUnitAbility),
                                     typeof (TerrianExtension),
                                     typeof (VehicleExtension),
                                     typeof (GameObjectExtension)
                                 };
            return knownTypes;
        }

        public static GameLevels Load(Stream stream)
        {
            var stringReader = new StreamReader(stream);
            var reader = XmlReader.Create(stringReader);

            var knownTypes = KnownTypes();

            var serializer =
                new DataContractSerializer(
                    typeof(GameLevels), knownTypes);

            return (GameLevels)serializer.ReadObject(reader);
        }
    }
}
